file_path = 'Er_a_pRpMtRtM.csv'; % Update this to your actual file path

% Open the file
fid = fopen(file_path, 'rt');
if fid == -1, error('Cannot open the file.'); end

% Read the first line for temperatures
tempLine = fgetl(fid);
tempCells = regexp(tempLine, '(?<=^|,)(\"[^\"]*\"|[^,]*)', 'match');
temperatures = str2double(tempCells(1:end)); % Convert from string to double

% Initialize variables based on the number of temperatures
numTemperatures = numel(temperatures);
magneticFields = [];
angles = cell(100, numTemperatures); % Predefine the size based on expected dimensions

% Process each subsequent line for magnetic fields and angles
lineIndex = 0; % Start line index at 0
while ~feof(fid)
    line = fgetl(fid);
    if isempty(line), continue; end % Skip empty lines
    lineIndex = lineIndex + 1; % Increment at the start of valid line processing
    cells = regexp(line, '(?<=^|,)(\"[^\"]*\"|[^,]*)', 'match');
    magneticFields(lineIndex, 1) = str2double(cells{1}); % First cell is the magnetic field

    for i = 2:length(cells)
        angleStr = cells{i};
        angleStr = erase(angleStr, '"'); % Remove quotes
        angles{lineIndex, i-1} = str2num(angleStr); % Convert string to numeric array, adjust index by -1
    end
end

fclose(fid); % Close the file

%============================================================================================

file_path2 = 'Er_a_MRzx.csv'; % Update this to your actual file path

% Open the file
fid2 = fopen(file_path2, 'rt');
if fid2 == -1, error('Cannot open the file.'); end

% Read and discard the first line (likely headers)
fgetl(fid2);

Mn_R = cell(100, numTemperatures); % Predefine the size based on expected dimensions from temperatures

lineIndex = 0; % Start line index at 0
while ~feof(fid2)
    line = fgetl(fid2);
    if isempty(line), continue; end % Skip empty lines
    lineIndex = lineIndex + 1; % Increment at the start of valid line processing
    cells = regexp(line, '(?<=^|,)(\"[^\"]*\"|[^,]*)', 'match');

    for i = 2:length(cells)
        Mn_RStr = cells{i};
        Mn_RStr = erase(Mn_RStr, '"'); % Remove quotes
        Mn_R{lineIndex, i-1} = str2num(Mn_RStr); % Convert string to numeric array, adjust index by -1
    end
end

fclose(fid2); % Close the file

%=============================================================================================
% Verify the corrected sizes of the loaded data
disp(['Corrected Size of magneticFields: ', num2str(size(magneticFields))]);
disp(['Corrected Size of temperatures: ', num2str(size(temperatures))]);
disp(['Corrected Size of angles matrix: ', num2str(size(angles))]);
disp(['Corrected Size of Mn_R matrix: ', num2str(size(Mn_R))]);
disp(['Generating data, this may take a couple minutes...']);
%================================================================
% Load and display the background image
imgPath = 'Er_a_v4.png'; % Update with your actual image file path
img = imread(imgPath);
figure; % Create a new figure
imagesc([min(temperatures), max(temperatures)], [min(magneticFields), max(magneticFields)], img);

set(gca, 'YDir','normal')
% Optionally adjust plot aspect ratio to match the image
imgInfo = imfinfo(imgPath); % Get image information
aspectRatio = imgInfo.Width / imgInfo.Height; % Calculate aspect ratio of the image
pbaspect([aspectRatio 1 1]); 

% Define buffers to create space around the scatter plot
xBuffer = (max(temperatures) - min(temperatures)) / 600; % 20% buffer
yBuffer = (max(magneticFields) - min(magneticFields)) /500;

% Adjust axis limits with additional buffer to "shrink" the scatter plot area
xlim([min(temperatures) - xBuffer, max(temperatures) + xBuffer]);
ylim([min(magneticFields) - yBuffer, max(magneticFields) + yBuffer]);

hold on; % Keep the image displayed while plotting points

% Calculate the flipped y-coordinates for the scatter plot

% Overlay data points on the image with flipped y-coordinates
for i = 1:numel(magneticFields)
    for j = 1:numel(temperatures)

        scatter(temperatures(j), magneticFields(i), 70, ... % 70 is the size of the marker
            'MarkerEdgeColor', 'none', ...
            'MarkerFaceColor', [0.7, 0.7, 0.7], ...
            'MarkerFaceAlpha', 0.1); % Adjust the edge width if needed
    end
end

% Enable data cursor mode and customize the callback function
dcm = datacursormode(gcf);
set(dcm, 'UpdateFcn', {@myupdatefcn, angles, temperatures, magneticFields, Mn_R});

% Define the callback function to display the angles
function txt = myupdatefcn(~, event_obj, angles, temperatures, magneticFields, Mn_R)
    pos = get(event_obj, 'Position');
    temp = pos(1); % X-coordinate corresponds to temperature
    magField = pos(2); % Y-coordinate corresponds to magnetic field

    % Find the closest data point indices
    [~, tempIdx] = min(abs(temperatures - temp));
    [~, magFieldIdx] = min(abs(magneticFields - magField));

    % Retrieve angles for the closest point
    angleValues = angles{magFieldIdx, tempIdx};
    Mn_R_Values = Mn_R{magFieldIdx, tempIdx};
    % Call the 3D plot function with the angle values 
    DrawVector2(angleValues, Mn_R_Values)

    % Prepare the text to display
    txt = {['Temperature: ', num2str(temp)], ...
           ['Magnetic Field: ', num2str(magField)], ...
           ['Angles: ', mat2str(angleValues, 4)], ...
           ['MnR_z_x: ', mat2str(Mn_R_Values, 2)]}; % Display angles with 4 decimal places
end
